﻿using Sundry.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace Sundry.App_Start.Common
{
    public class UploadImgHelper
    {
        public static readonly string[] _productImgSize = { "S", "M", "L", "XL","XXL","XXXL" };//200*200,300*300,450*450,600*600,1000*1000


        #region 保存图片 返回说明【-1：表示未提供上传文件;-2:表示图片格式不对;-3:表示上传文件超出可上传大小,如果成功则返回图片路径】
        /// <summary>
        /// 上传普通图片，只保存原图
        /// </summary>
        /// <param name="uid">用户Id</param>
        /// <param name="imgFile">上传文件</param>
        /// <param name="module">上传类型，用于定义保存图片的文件夹路径</param>
        /// <returns>返回说明【-1：表示未提供上传文件;-2:表示图片格式不对;-3:表示上传文件超出可上传大小,如果成功则返回图片路径】</returns>
        public static string SaveUploadImage(string uid, HttpPostedFileBase imgFile, string module)
        {
            if (imgFile == null) return "-1";

            Sundry.Model.UploadSet uploadSet = Sundry.App_Start.Common.SetHelper.GetUploadSet();
            //判断文件格式是否正确
            string fileName = imgFile.FileName;
            string extension = Path.GetExtension(fileName);
            if (!ValidateHelper.IsImgFileName(fileName) || !ValidateHelper.IsInArray(extension, uploadSet.UploadImgType))return "-2";

            //判断文件大小是否符合
            int fileSize = imgFile.ContentLength;
            if (fileSize > uploadSet.UploadImgSize) return "-3";

            string path = string.Format("/Upload/{0}/{1}/{2}/",uid, module,DateTime.Now.ToString("yyyyMMdd"));
            string dirPath = PubliFunction.GetMapPath(path);
            string newFileName = string.Format("{0}{1}", DateTime.Now.ToString("yyMMddHHmmssfffffff"), extension);

            string sourceDirPath = dirPath + "Source/";
            if (!Directory.Exists(sourceDirPath))
                Directory.CreateDirectory(sourceDirPath);

            string sourcePath = sourceDirPath + newFileName;
            imgFile.SaveAs(sourcePath);
            return path + "Source/" + newFileName;
        }
        /// <summary>
        /// 上传品牌图片
        /// </summary>
        /// <param name="Base64Str">64位图片字符串</param>
        /// <param name="fileName">图片名称（包括后缀）</param>
        /// <param name="uid">用户Id</param>
        /// <returns>返回说明【-1：表示未提供上传文件;-2:表示图片格式不对;-3:表示上传文件超出可上传大小,如果成功则返回图片路径】</returns>
        public static string SaveBrandImg(string Base64Str,string fileName,string uid)
        {
            if (string.IsNullOrEmpty(Base64Str)) return "-1";

            byte[] buffer = Convert.FromBase64String(Base64Str);
            Sundry.Model.UploadSet uploadSet = Sundry.App_Start.Common.SetHelper.GetUploadSet();
            //判断文件格式是否正确
            string extension = Path.GetExtension(fileName);
            if (!ValidateHelper.IsImgFileName(fileName) || !ValidateHelper.IsInArray(extension, uploadSet.UploadImgType)) return "-2";
            //判断图片大小是否符合
            if (buffer.Length > uploadSet.UploadImgSize) return "-3";

            string path = string.Format("/Upload/BrandImg/{0}/{1}/", uid, DateTime.Now.ToString("yyyyMMdd"));
            string dirPath = ValidateHelper.GetMapPath(path);
            string sourceDirPath = string.Format("{0}source/", dirPath);
            if (!System.IO.Directory.Exists(sourceDirPath))
            {
                System.IO.Directory.CreateDirectory(sourceDirPath);
            }
            string sourcePath = sourceDirPath + fileName;
            System.IO.FileStream fs = new System.IO.FileStream(sourcePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
            fs.Write(buffer, 0, buffer.Length);
            fs.Flush();
            fs.Close();

            //生成品牌缩略图
            if (uploadSet.WatermarkType == 1)//文字水印
            {
                string pathtext = string.Format("{0}{1}_text{2}", sourceDirPath, fileName, extension);
                IoImgHelper.GenerateTextWatermark(sourcePath, path, uploadSet.WatermarkText, uploadSet.WatermarkTextSize, uploadSet.WatermarkTextFont, uploadSet.WatermarkPosition, uploadSet.WatermarkQuality);
                sourcePath = pathtext;
            }
            else if (uploadSet.WatermarkType == 2)//图片水印
            {
                string pathimg = string.Format("{0}{1}_img{2}", sourceDirPath, fileName, extension);
                string watermarkPath = ValidateHelper.GetMapPath("/watermarks/" + uploadSet.WatermarkImg);
                IoImgHelper.GenerateImageWatermark(sourcePath, watermarkPath, path, uploadSet.WatermarkPosition, uploadSet.WatermarkImgOpacity, uploadSet.WatermarkQuality);
                sourcePath = pathimg;
            }
            string[] sizeList = StringHelper.SplitString(uploadSet.BrandThumbSize);
            for (int i = 0; i < sizeList.Length; i++)
            {
                string thumbDirPath = string.Format("{0}thumb{1}/", dirPath, _productImgSize[i]);
                if (!Directory.Exists(thumbDirPath))
                    Directory.CreateDirectory(thumbDirPath);
                string[] widthAndHeight = StringHelper.SplitString(sizeList[i], "_");
                IoImgHelper.GenerateThumb(sourcePath,
                                       thumbDirPath + fileName,
                                       TypeHelper.StringToInt(widthAndHeight[0]),
                                       TypeHelper.StringToInt(widthAndHeight[1]),
                                       "Cut");
            }

            return path + "Source/" + fileName;
        }
        #endregion



        public static string SaveUplaodProductImage(int storeId, HttpPostedFileBase productImage, string module, string time)
        {
            if (productImage == null)
                return "-1";

            Sundry.Model.UploadSet mallConfig = Sundry.App_Start.Common.SetHelper.GetUploadSet();
            string fileName = productImage.FileName;
            string extension = Path.GetExtension(fileName);
            if (!ValidateHelper.IsImgFileName(fileName) || !ValidateHelper.IsInArray(extension, mallConfig.UploadImgType))
                return "-2";

            int fileSize = productImage.ContentLength;
            if (fileSize > mallConfig.UploadImgSize)
                return "-3";
            string path = string.Format("/upload/{0}/{1}/{2}/", module, storeId, time);
            string dirPath = ValidateHelper.GetMapPath(path);
            string name = "ps_" + DateTime.Now.ToString("yyMMddHHmmssfffffff");
            string newFileName = name + extension;
            string[] sizeList = StringHelper.SplitString(mallConfig.ProductShowThumbSize);
            string sourceDirPath = string.Format("{0}source/", dirPath);
            if (!Directory.Exists(sourceDirPath))
                Directory.CreateDirectory(sourceDirPath);
            string sourcePath = sourceDirPath + newFileName;
            productImage.SaveAs(sourcePath);

            if (mallConfig.WatermarkType == 1)//文字水印
            {
                string pathtext = string.Format("{0}{1}_text{2}", sourceDirPath, name, extension);
                IoImgHelper.GenerateTextWatermark(sourcePath, path, mallConfig.WatermarkText, mallConfig.WatermarkTextSize, mallConfig.WatermarkTextFont, mallConfig.WatermarkPosition, mallConfig.WatermarkQuality);
                sourcePath = pathtext;
            }
            else if (mallConfig.WatermarkType == 2)//图片水印
            {
                string pathimg = string.Format("{0}{1}_img{2}", sourceDirPath, name, extension);
                string watermarkPath = ValidateHelper.GetMapPath("/watermarks/" + mallConfig.WatermarkImg);
                IoImgHelper.GenerateImageWatermark(sourcePath, watermarkPath, path, mallConfig.WatermarkPosition, mallConfig.WatermarkImgOpacity, mallConfig.WatermarkQuality);
                sourcePath = pathimg;
            }
            for (int i = 0; i < sizeList.Length; i++)
            {
                string thumbDirPath = string.Format("{0}thumb{1}/", dirPath, _productImgSize[i]);
                if (!Directory.Exists(thumbDirPath))
                    Directory.CreateDirectory(thumbDirPath);
                string[] widthAndHeight = StringHelper.SplitString(sizeList[i], "_");
                IoImgHelper.GenerateThumb(sourcePath,
                                       thumbDirPath + newFileName,
                                       TypeHelper.StringToInt(widthAndHeight[0]),
                                       TypeHelper.StringToInt(widthAndHeight[1]),
                                       "Cut");
            }
            return path + "source/" + newFileName;
        }
    }
}